package login

import (
	"chess_platform/internal/login/fetch"
	"encoding/json"
	"errors"
	"fmt"
)

//闲聊登录接入
const (
	XianLiaoAppID     = "Z3eJlhOuFSpPkRcz"
	XianLiaoAppSecret = "fU7pd8Eu3T51LdTS"
)

type XianLiaoToken struct {
	ErrCode int64  `json:"err_code"`
	ErrMsg  string `json:"err_msg"`
	Data    struct {
		AccessToken  string `json:"access_token"`
		RefreshToken string `json:"refresh_token"`
		ExpiresIn    int64  `json:"expires_in"`
	} `json:"data"`
}

//通过code来获取aceess_token及open_id
func GetXianLiaoOpenIdAccessToken(code string) (*XianLiaoToken, error) {
	url := fmt.Sprintf("https://ssgw.updrips.com/oauth2/accessToken?"+
		"appid=%v&appsecret=%v&code=%v&grant_type=authorization_code", XianLiaoAppID, XianLiaoAppSecret, code)

	body, err := fetch.Cmd(fetch.Request{
		Method: "POST",
		URL:    url,
	})
	if err != nil {
		return nil, err
	}
	var result XianLiaoToken
	err = json.Unmarshal(body, &result)
	if err != nil {
		return &result, err
	}
	if result.ErrCode != 0 {
		return &result, errors.New(result.ErrMsg)
	}
	return &result, err
}

type XianLiaoUserInfo struct {
	ErrCode int64  `json:"err_code"`
	ErrMsg  string `json:"err_msg"`
	Data    struct {
		OpenId         string `json:"openId"`
		Nickname       string `json:"nickName"`
		OriginalAvatar string `json:"originalAvatar"`
		SmallAvatar    string `json:"smallAvatar"`
	} `json:"data"`
}

func getXianLiaoUserInfo(accessToken string) (*XianLiaoUserInfo, error) {
	url := fmt.Sprintf("https://ssgw.updrips.com/resource/user/getUserInfo?access_token=%s", accessToken)
	body, err := fetch.Cmd(fetch.Request{
		Method: "GET",
		URL:    url,
	})
	if err != nil {
		return nil, err
	}
	var result XianLiaoUserInfo
	err = json.Unmarshal(body, &result)
	return &result, err
}

func GetXianLiaoUserInfo(accessToken string) (*XianLiaoUserInfo, error) {
	return getXianLiaoUserInfo(accessToken)
}
